<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请人" prop="personnelIdName">
        <el-input
          v-model="queryParams.personnelIdName"
          placeholder="请输入申请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="研究方向" prop="deptIdName">
        <el-input
          v-model="queryParams.deptIdName"
          placeholder="请输入申请部门/研究方向"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据日期" prop="vouchDate">
        <el-date-picker clearable
          v-model="queryParams.vouchDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择单据日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="合同总金额" prop="contractTotalAmount">
        <el-input
          v-model="queryParams.contractTotalAmount"
          placeholder="请输入合同总金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同分类名称" prop="contractCategoryName">
        <el-input
          v-model="queryParams.contractCategoryName"
          placeholder="请输入合同分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同履行期限" prop="contractDurationMonths">
        <el-input
          v-model="queryParams.contractDurationMonths"
          placeholder="请输入合同履行期限"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="审批状态" prop="approveStatus">
         <el-select v-model="queryParams.approveStatus" placeholder="请选择审批状态" clearable>
                    <el-option
                      v-for="dict in dict.type.yy_bip_construct_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sci:construct:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sci:construct:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sci:construct:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sci:construct:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="constructList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="申请人" align="center" prop="personnelIdName" />
      <el-table-column label="申请部门/研究方向" align="center" prop="deptIdName" />
      <el-table-column label="单据日期" align="center" prop="vouchDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.vouchDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同名称" align="center" prop="contractName" />
      <el-table-column label="合同总金额" align="center" prop="contractTotalAmount" />
      <el-table-column label="合同分类名称" align="center" prop="contractCategoryName" />
      <el-table-column label="合同履行期限" align="center" prop="contractDurationMonths" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" />
       <el-table-column label="审批状态" align="center" prop="approveStatus" >
         <template slot-scope="scope">
            <dict-tag :options="dict.type.yy_bip_construct_status" :value="scope.row.approveStatus"/>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sci:construct:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sci:construct:remove']"
          >删除</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleView(scope.row)"
            v-hasPermi="['sci:construct:query']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用友合同数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申请人" prop="personnelIdName">
          <el-input v-model="form.personnelIdName" placeholder="请输入申请人" />
        </el-form-item>
        <el-form-item label="申请部门/研究方向" prop="deptIdName">
          <el-input v-model="form.deptIdName" placeholder="请输入申请部门/研究方向" />
        </el-form-item>
        <el-form-item label="签约单位名称" prop="orgIdName">
          <el-input v-model="form.orgIdName" placeholder="请输入签约单位名称" />
        </el-form-item>
        <el-form-item label="单据日期" prop="vouchDate">
          <el-date-picker clearable
            v-model="form.vouchDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择单据日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同号" prop="contractCode">
          <el-input v-model="form.contractCode" placeholder="请输入合同号" />
        </el-form-item>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="合同总金额" prop="contractTotalAmount">
          <el-input v-model="form.contractTotalAmount" placeholder="请输入合同总金额" />
        </el-form-item>
        <el-form-item label="合同分类名称" prop="contractCategoryName">
          <el-input v-model="form.contractCategoryName" placeholder="请输入合同分类名称" />
        </el-form-item>
        <el-form-item label="集中采购部门" prop="centralizedProcurementDept">
          <el-input v-model="form.centralizedProcurementDept" placeholder="请输入集中采购部门" />
        </el-form-item>
        <el-form-item label="采购申请单号" prop="procurementApplyCode">
          <el-input v-model="form.procurementApplyCode" placeholder="请输入采购申请单号" />
        </el-form-item>
        <el-form-item label="是否固定期限合同" prop="isFixedTermContract">
          <el-input v-model="form.isFixedTermContract" placeholder="请输入是否固定期限合同" />
        </el-form-item>
        <el-form-item label="计划生效日期" prop="plannedEffectiveDate">
          <el-date-picker clearable
            v-model="form.plannedEffectiveDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划生效日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划终止日期" prop="plannedTerminationDate">
          <el-date-picker clearable
            v-model="form.plannedTerminationDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划终止日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同履行期限" prop="contractDurationMonths">
          <el-input v-model="form.contractDurationMonths" placeholder="请输入合同履行期限" />
        </el-form-item>
        <el-form-item label="是否敞口合同" prop="isOpenContract">
          <el-input v-model="form.isOpenContract" placeholder="请输入是否敞口合同" />
        </el-form-item>
        <el-form-item label="到货/服务时间要求" prop="deliveryTimeRequirement">
          <el-input v-model="form.deliveryTimeRequirement" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="资金来源" prop="fundingSource">
          <el-input v-model="form.fundingSource" placeholder="请输入资金来源" />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="供应商银行账号" prop="supplierBankAccount">
          <el-input v-model="form.supplierBankAccount" placeholder="请输入供应商银行账号" />
        </el-form-item>
        <el-form-item label="供应商开户行名称" prop="supplierBankName">
          <el-input v-model="form.supplierBankName" placeholder="请输入供应商开户行名称" />
        </el-form-item>
        <el-form-item label="供应商联行号" prop="supplierBankCode">
          <el-input v-model="form.supplierBankCode" placeholder="请输入供应商联行号" />
        </el-form-item>
        <el-form-item label="开具发票税率" prop="invoiceTaxRate">
          <el-input v-model="form.invoiceTaxRate" placeholder="请输入开具发票税率" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 查看抽屉 -->
    <el-drawer
      title="合同详情"
      :visible.sync="drawer"
      size="50%"
      direction="rtl"
    >

      <!-- 自定义标题插槽 -->
  <div slot="title" class="drawer-title">
    <span>采购需求详情</span>
    <el-tag 
      :type="getStatusTagType(formView.approveStatus)"
      size="medium"
      style="margin-left: 10px;"
    >
      <dict-tag 
        :options="dict.type.yy_bip_construct_status" 
        :value="formView.approveStatus"
      />
    </el-tag>
  </div>
      <!-- 第一部分 - 指定字段分组 -->
      <el-card shadow="always" style="margin: 20px;">
        <el-descriptions title="基本信息" :column="2" border>
           <el-descriptions-item label="签约单位名称">{{ formView.orgIdName }}</el-descriptions-item>
          <el-descriptions-item label="研究方向">{{ formView.deptIdName }}</el-descriptions-item>
           <el-descriptions-item label="单据日期">{{ parseTime(formView.vouchDate, '{y}-{m}-{d}') }}</el-descriptions-item>
            <el-descriptions-item label="合同号">{{ formView.contractCode }}</el-descriptions-item>
          <el-descriptions-item label="合同名称">{{ formView.contractName }}</el-descriptions-item>
          <el-descriptions-item label="合同分类名称">{{ formView.contractCategoryName }}</el-descriptions-item>
          <el-descriptions-item label="货物/服务名称">{{ formView.goodsServiceName }}</el-descriptions-item>
          <el-descriptions-item label="合同总金额">{{ formView.contractTotalAmount }}</el-descriptions-item>
          <el-descriptions-item label="合同履行期限">{{ formView.contractDurationMonths }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ formView.personnelIdName }}</el-descriptions-item>
            <el-descriptions-item label="集中采购部门">{{ formView.centralizedProcurementDept }}</el-descriptions-item>
          <el-descriptions-item label="采购申请单号">{{ formView.procurementApplyCode }}</el-descriptions-item>
          <el-descriptions-item label="是否固定期限合同">{{ formView.isFixedTermContract }}</el-descriptions-item>
          <el-descriptions-item label="计划生效日期">{{ parseTime(formView.plannedEffectiveDate, '{y}-{m}-{d}') }}</el-descriptions-item>
          <el-descriptions-item label="计划终止日期">{{ parseTime(formView.plannedTerminationDate, '{y}-{m}-{d}') }}</el-descriptions-item>
          <el-descriptions-item label="是否敞口合同">{{ formView.isOpenContract }}</el-descriptions-item>
          <el-descriptions-item label="到货/服务时间要求">{{ formView.deliveryTimeRequirement }}</el-descriptions-item>
          <el-descriptions-item label="资金来源">{{ formView.fundingSource }}</el-descriptions-item>
         
        </el-descriptions>
      </el-card>

      <!-- 第二部分 - 其余字段 -->
      <el-card shadow="always" style="margin: 20px;">
        <el-descriptions title="签约信息" :column="2" border>
           <el-descriptions-item label="供应商">{{ formView.supplierName }}</el-descriptions-item>
          <el-descriptions-item label="供应商银行账号">{{ formView.supplierBankAccount }}</el-descriptions-item>
          <el-descriptions-item label="供应商开户行名称">{{ formView.supplierBankName }}</el-descriptions-item>
          <el-descriptions-item label="供应商联行号">{{ formView.supplierBankCode }}</el-descriptions-item>
          <el-descriptions-item label="开具发票税率">{{ formView.invoiceTaxRate }}</el-descriptions-item>
           <el-descriptions-item label="开具发票种类">{{ formView.invoiceType }}</el-descriptions-item>
        </el-descriptions>
      </el-card>


       <el-card shadow="always" style="margin: 20px;">
      <div class="card-title">合同标的物</div>
      <el-table 
        :data="contractDetailList" 
        border 
        style="width: 100%; margin-top: 10px;"
        v-loading="loadingContractDetail"
      >
        <el-table-column label="费用项目" align="center" prop="expenseitemName" />
        <el-table-column label="货物编码" align="center" prop="goodsCode" />
        <el-table-column label="货物名称" align="center" prop="goodsName" />
        <el-table-column label="计量单位" align="center" prop="measurementUnit" />
        <el-table-column label="数量" align="center" prop="quantity" />
        <el-table-column label="单价" align="center" prop="unitPrice" />
        <el-table-column label="金额" align="center" prop="amount" />
        <el-table-column label="税率" align="center" prop="taxRate" />
        <el-table-column label="税额" align="center" prop="taxAmount" />
        <el-table-column label="含税单价" align="center" prop="unitPriceWithTax" />
        <el-table-column label="含税金额" align="center" prop="amountWithTax" />
        <el-table-column label="规格说明" align="center" prop="specification" />
      </el-table>
    </el-card>

    <!-- 付款计划卡片 -->
    <el-card shadow="always" style="margin: 20px;">
      <div class="card-title">付款计划</div>
      <el-table 
        :data="payPlanList" 
        border 
        style="width: 100%; margin-top: 10px;"
        v-loading="loadingPayPlan"
      >
        <el-table-column label="付款计划名称" align="center" prop="paymentPlanName" />
        <el-table-column label="付款比例" align="center" prop="paymentPlanRatio">
          <template slot-scope="scope">
            {{ scope.row.paymentPlanRatio }}%
          </template>
        </el-table-column>
        <el-table-column label="付款类型" align="center" prop="paymentType" />
        <el-table-column label="付款条件" align="center" prop="paymentCondition" />
        <el-table-column label="计划金额" align="center" prop="paymentPlanAmount" />
      </el-table>
    </el-card>
    </el-drawer>

  </div>
</template>

<script>
import { listConstruct, getConstruct, delConstruct, addConstruct, updateConstruct, getContractDetails,
  getPayPlans } from "@/api/sci/construct";

export default {
  name: "Construct",
  dicts:['yy_bip_construct_status'],
  data() {
    return {
      contractDetailList: [],     // 合同标的物数据
      payPlanList: [],            // 付款计划数据
      loadingContractDetail: false, // 标的物加载状态
      loadingPayPlan: false,        // 付款计划加载状态
        // ... 其他数据保持不变 ...
      drawer: false, // 控制抽屉显示
      formView: {},   // 查看表单数据
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用友合同数据表格数据
      constructList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        personnelIdName: null,
        deptIdName: null,
        vouchDate: null,
        contractName: null,
        contractTotalAmount: null,
        contractCategoryName: null,
        contractDurationMonths: null,
        supplierName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
     /** 查看按钮操作 */
    handleView(row) {
      this.drawer = true;
      this.loadingContractDetail = true;
      this.loadingPayPlan = true;

      // 清空数据
      this.contractDetailList = [];
      this.payPlanList = [];
      this.formView = {};
      const contractCode = row.contractCode;
      const id = row.id || this.ids;
      getConstruct(id).then(response => {
        this.formView = response.data;
        
         // 获取合同标的物
        getContractDetails(contractCode).then(contractDetails => {
          this.contractDetailList = contractDetails.data;
          this.loadingContractDetail = false;
        }).catch(() => {
          this.loadingContractDetail = false;
          this.drawer = true;
          this.contractDetailList = [];
        });

        // 获取付款计划
        getPayPlans(contractCode).then(payPlans => {
          this.payPlanList = payPlans.data;
          this.loadingPayPlan = false;
        }).catch(() => {
          this.loadingPayPlan = false;
          this.payPlanList = [];
          this.drawer = true;
        });
      });
    },
    
    // 时间格式化方法
    parseTime(time, format = '{y}-{m}-{d}') {
      if (!time) return '';
      let date = new Date(time);
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds()
      };
      return format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        return value.toString().padStart(2, '0');
      });
    },
    /** 查询用友合同数据列表 */
    getList() {
      this.loading = true;
      listConstruct(this.queryParams).then(response => {
        this.constructList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        personnelIdName: null,
        deptIdName: null,
        orgIdName: null,
        vouchDate: null,
        contractCode: null,
        contractName: null,
        contractTotalAmount: null,
        contractCategoryName: null,
        centralizedProcurementDept: null,
        procurementApplyCode: null,
        isFixedTermContract: null,
        plannedEffectiveDate: null,
        plannedTerminationDate: null,
        contractDurationMonths: null,
        isOpenContract: null,
        deliveryTimeRequirement: null,
        fundingSource: null,
        supplierName: null,
        supplierBankAccount: null,
        supplierBankName: null,
        supplierBankCode: null,
        invoiceType: null,
        invoiceTaxRate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用友合同数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getConstruct(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用友合同数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConstruct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConstruct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用友合同数据编号为"' + ids + '"的数据项？').then(function() {
        return delConstruct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sci/construct/export', {
        ...this.queryParams
      }, `construct_${new Date().getTime()}.xlsx`)
    },
      getStatusTagType(status) {
    switch(status) {
      case 0: return 'info';    // 自由
      case 3: return 'warning'; // 审批中
      case 6665: return 'success'; // 生效
      case 1: return 'success'; // 审批通过
      case 6669: return 'success'; // 完成
      case 6666: 'danger';   // 冻结
      case 6667: 'danger';   // 终止
      case 2: 'danger';   // 审批不通过
      case 6668: 'warning';   // 变更中 
      default: return 'info';
    }
  },
  }
};
</script>

<style scoped>
/* 添加抽屉内容的样式 */
.el-drawer__body {
  padding: 0;
  overflow-y: auto;
}

.el-card {
  margin-bottom: 15px;
}

.el-descriptions__title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.card-title{
   font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}
</style>
